package jwt

import (
	"net/http"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"

	"github.com/EDDYCJY/go-gin-example/pkg/e"
	"github.com/EDDYCJY/go-gin-example/pkg/util"
)

// JWT is jwt middleware
func JWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		var ferror = e.FResult_OK
		var data interface{}
		var claims *util.Claims
		var err error
		token := c.GetHeader("token")
		if token == "" {
			ferror = e.FResult{ErrCode: e.ERROR, ErrMsg: "用户未登录"}
		} else {
			claims, err = util.ParseToken(token)
			if err != nil {
				switch err.(*jwt.ValidationError).Errors {
				case jwt.ValidationErrorExpired:
					ferror = e.FResult{ErrCode: e.ERROR, ErrMsg: "登录已过期，请重新登录"}
				default:
					ferror = e.FResult{ErrCode: e.ERROR, ErrMsg: "请重新登录"}
				}
			}
		}

		if ferror.ErrCode != e.SUCCESS {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": ferror.ErrCode,
				"msg":  ferror.ErrMsg,
				"data": data,
			})

			c.Abort()
			return
		}
		c.Set("user_id", claims.UserId)
		c.Next()
	}
}
